package top.rish.utils.excel.convert;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * 转为日期
 */
public class ConvertToDate implements ExcelDataConvertTo<Date> {


    /**
     * 日期正则和日期格式
     */
    private static final Map<String,String> REG_MAP = new ConcurrentHashMap<String,String>(){
        {
            put("\\d{1,2}\\/\\d{1,2}\\/\\d{2} \\d{1,2}:\\d{1,2}",                                 "MM/DD/yy HH:mm");
            put("\\d{1,2}-\\d{1,2}-\\d{2} \\d{1,2}:\\d{1,2}",                                     "MM-DD-yy HH:mm");
            put("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}",                            "yyyy-MM-dd HH:mm:ss");
            put("\\d{4}\\/\\d{1,2}\\/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}",                        "yyyy/MM/dd HH:mm:ss");
            put("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}",                                     "yyyy-MM-dd HH:mm");
            put("\\d{4}\\/\\d{1,2}\\/\\d{1,2} \\d{1,2}:\\d{1,2}",                                 "yyyy/MM/dd HH:mm");
            put("\\d{4}\\/\\d{1,2}\\/\\d{1,2} \\d{1,2}:\\d{1,2} [^\\x00-\\xff|a-zA-Z]{2}",        "yyyy/MM/dd HH:mm aa");
            put("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2} [^\\x00-\\xff|a-zA-Z]{2}",            "yyyy-MM-dd HH:mm aa");
        }
    };

    @Override
    public boolean required() {
        return true;
    }

    @Override
    public Date convert(String data ) throws Exception {
        for(Map.Entry<String,String> entry:REG_MAP.entrySet()){
            String pattern = entry.getKey();
            String format = entry.getValue();
            if(Pattern.matches(pattern, data)){
               return new SimpleDateFormat(format, Locale.CHINA).parse(data);
            }
        }
        throw new Exception("暂无此日期格式 "+data);
    }
}
